//
//  ZLModel.m
//  ZLClient
//
//  Created by lizhu on 2017/6/26.
//  Copyright © 2017年 zhuli. All rights reserved.
//

#import "ZLModel.h"
#import <objc/message.h>

@interface ZLModel ()
@property (nonatomic,copy) NSString *address;

@end

@implementation ZLModel
- (instancetype)init {
    self = [super init];
    if (self) {
        _address = @"私有属性北京";
        self.name = @"孟孟";
    }
    return self;
}
//公共方法
- (void)publicMethod {
    NSLog(@"对外暴露的方法 %@",self.address);
}
//私有方法
- (void)privateMethod {
    NSLog(@"私有方法%@",self.name);
}
- (NSString *)description {
    return [NSString stringWithFormat:@" %@,  %@",self.address,self.name];
}

#pragma mark - NSCoding
- (void)encodeWithCoder:(NSCoder *)encoder {
    unsigned int count = 0;
    //  利用runtime获取实例变量的列表
    Ivar *ivars = class_copyIvarList([self class], &count);
    for (int i = 0; i < count; i ++) {
        //  取出i位置对应的实例变量
        Ivar ivar = ivars[i];
        //  查看实例变量的名字
        const char *name = ivar_getName(ivar);
        //  C语言字符串转化为NSString
        NSString *nameStr = [NSString stringWithCString:name encoding:NSUTF8StringEncoding];
        //  利用KVC取出属性对应的值
        id value = [self valueForKey:nameStr];
        //  归档
        [encoder encodeObject:value forKey:nameStr];
    }
    
    //  记住C语言中copy出来的要进行释放
    free(ivars);
    
}

- (id)initWithCoder:(NSCoder *)decoder {
    if (self = [super init]) {
        unsigned int count = 0;
        Ivar *ivars = class_copyIvarList([self class], &count);
        for (int i = 0; i < count; i ++) {
            Ivar ivar = ivars[i];
            const char *name = ivar_getName(ivar);
            
            //
            NSString *key = [NSString stringWithCString:name encoding:NSUTF8StringEncoding];
            id value = [decoder decodeObjectForKey:key];
            //  设置到成员变量身上
            [self setValue:value forKey:key];
        }
        
        free(ivars);
    }
    return self;
}

#pragma mark - 动态的添加方法
// 默认方法都有两个隐式参数，
void eat(id self,SEL sel){
    NSLog(@"%@ %@",self,NSStringFromSelector(sel));
    NSLog(@"动态添加了一个方法");
}

// 当一个对象调用未实现的方法，会调用这个方法处理,并且会把对应的方法列表传过来.
// 刚好可以用来判断，未实现的方法是不是我们想要动态添加的方法
+ (BOOL)resolveInstanceMethod:(SEL)sel {
    
    if (sel == NSSelectorFromString(@"eat")) {
        // 注意:这里需要强转成IMP类型
        class_addMethod(self, sel, (IMP)eat, "v@:");
        return YES;
    }
    // 先恢复, 不然会覆盖系统的方法
    return [super resolveInstanceMethod:sel];
}
@end
